package com.twetec.cms.adapter.pc.backend.tag;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import com.twetec.cms.adapter.pc.backend.tag.annotation.TplTag;
import com.twetec.cms.adapter.pc.backend.tag.doc.TagDocObject;
import com.twetec.cms.common.constant.ArticleEnum;
import com.twetec.cms.common.util.validate.ValidateUtil;
import com.twetec.cms.model.po.website.*;
import com.twetec.cms.service.website.*;
import org.apache.commons.lang3.StringUtils;
import org.beetl.core.tag.GeneralVarTagBinding;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service()
@Scope("prototype")
@TplTag("articleList")
public class ArticleListTag extends GeneralVarTagBinding {

	@Autowired
	private ArticleService articleService;

	@Autowired
	private ColumnService columnService;

	@Autowired
	private SiteService siteService;

	@Autowired
	private ArticleExtendService articleExtendService;



	@Override
	public void render() {
		System.out.println("ArticleListTag");

		// 接收标签参数
		Map result = Maps.newHashMap();

		// 栏目id
		Long columnId = (this.getAttributeValue("columnId") instanceof String) ?
				Long.parseLong((String) this.getAttributeValue("columnId")) : (Long) this.getAttributeValue("columnId");

		// 页面
		Integer page = (this.getAttributeValue("page") instanceof String) ?
				Integer.parseInt((String) this.getAttributeValue("page")) : (Integer) this.getAttributeValue("page");
		if (null == page) page = 1;

		// 页面容量
		Integer limit = (this.getAttributeValue("limit") instanceof String) ?
				Integer.parseInt((String) this.getAttributeValue("limit")) : (Integer) this.getAttributeValue("limit");
		if (null == limit) limit = 15;

		// 资讯发布系统的域名
		String serverUrl = (String) this.getAttributeValue("serverUrl");


		// 标记是预览checkPage还是静态化staticPage/null
//		String pageType = (String) this.getAttributeValue("pageType");

		QueryWrapper<ArticlePO> articlePOQueryWrapper = new QueryWrapper<>();
		articlePOQueryWrapper.eq("COLUMN_ID", columnId);
		articlePOQueryWrapper.eq("IS_RECOVERY", 0);
		articlePOQueryWrapper.eq("ARTICLE_STATUS", ArticleEnum.STATUS_YI_FA_BU.getValue());
		articlePOQueryWrapper.orderByDesc("SORT");
		articlePOQueryWrapper.orderByAsc("ID");
		Page<ArticlePO> articlePOPage = articleService.page(new Page<>(page, limit), articlePOQueryWrapper);
		List<ArticlePO> records = articlePOPage.getRecords();

		if (!ValidateUtil.isNullOrEmpty(records)) {

			// 查询文章对应的站点的信息
			SitePO sitePO = siteService.getById(records.get(0).getSiteId());

			// 拼上站点的域名
//			String articleUrl = sitePO.getDomainUrl();
			String articleUrl = "";

			// 栏目的静态文件存储路径
			ColumnPO columnPO = columnService.getById(columnId);

			if (StringUtils.isEmpty(columnPO.getEncodedXpath())) return ;
			articleUrl = articleUrl + columnPO.getEncodedXpath() + "/article";

			if (!ValidateUtil.isNullOrEmpty(records)) {
				for (ArticlePO articlePO : records) {

					// 文章标题
					String title = articlePO.getTitle();
					// 发布时间 Date
					String releaseTime = DateUtil.formatDateTime(articlePO.getReleaseTime());
					// 对应url
					String url = articleUrl + '/' + articlePO.getId() + ".html";
					// 属性
					String attribute = articlePO.getAttribute();
					// 公告开始时间
					String gmtAnnouncementStart = DateUtil.formatDateTime(articlePO.getGmtAnnouncementStart());
					// 公告结束时间
					String gmtAnnouncementEnd = DateUtil.formatDateTime(articlePO.getGmtAnnouncementEnd());
					// 封面类型
					String coverType = articlePO.getCoverType();
					// 来源
					String origin = articlePO.getOrigin();
					// 作者
					String author = articlePO.getAuthor();

					// 封面
					List<Map<String,String>> coverMapList = new ArrayList<Map<String, String>>();
					// 将json字符数组转化为对象
					List<UrlConvert> urlConvertList = JSONArray.parseArray(articlePO.getCover(), UrlConvert.class);
					// 遍历，添加到map中
					if (!ValidateUtil.isNullOrEmpty(urlConvertList)) {
						for (UrlConvert urlConvert : urlConvertList) {
							HashMap<String, String> coverMap = new HashMap<>();
							coverMap.put("url", urlConvert.getFileUrl());
							coverMapList.add(coverMap);
						}
					}
					// 扩展字段
					QueryWrapper<ArticleExtendPO> articleExtendPOQueryWrapper = new QueryWrapper<>();
					articleExtendPOQueryWrapper.eq("ARTICLE_ID", articlePO.getId());

					if (ArticleEnum.TYPE_TIAO_ZHUAN_LIAN_JIE.getValue().equals(articlePO.getType()) || ArticleEnum.TYPE_XIA_ZAI_WEN_JIAN.getValue().equals(articlePO.getType())) {
						articleExtendPOQueryWrapper.select("EXTEND_FIELD_LIST", "CONTENT");
					}else {
						articleExtendPOQueryWrapper.select("EXTEND_FIELD_LIST");
					}
					ArticleExtendPO articleExtendPO = articleExtendService.getOne(articleExtendPOQueryWrapper);

					// 将扩展字段转换为集合再存放到map中
					HashMap<String, String> extendHashMap = new HashMap<>();
					if (!ValidateUtil.isNullOrEmpty(articleExtendPO)) {
						List<ExtendField> fieldList = JSON.parseArray(articleExtendPO.getExtendFieldList(), ExtendField.class);
						if (null != fieldList && !ValidateUtil.isNullOrEmpty(fieldList)) {
							for (ExtendField extendField : fieldList) {
								extendHashMap.put(extendField.getFieldCode(), extendField.getDefaultValue());

							}
						}
					}

					// 如果文章类型是下载文件
					if (ArticleEnum.TYPE_XIA_ZAI_WEN_JIAN.getValue().equals(articlePO.getType())) {
						// 获取地址
						UrlConvert urlConvert = JSON.parseObject(articleExtendPO.getContent(), UrlConvert.class);
						url = urlConvert.getFileUrl();
						// 如果是跳转链接
					} else if (ArticleEnum.TYPE_TIAO_ZHUAN_LIAN_JIE.getValue().equals(articlePO.getType())){
						url = articleExtendPO.getContent();
					}

					// 发布时间按日月统计
					String releaseTimeMonthDay = (DateUtil.month(articlePO.getReleaseTime()) + 1) + "-" + DateUtil.dayOfMonth(articlePO.getReleaseTime());

					// 返回标签参数
					result.put("title", title);
					result.put("releaseTime", releaseTime);
					result.put("releaseTimeMonthDay", releaseTimeMonthDay);
					result.put("attribute", attribute);
					result.put("gmtAnnouncementStart", gmtAnnouncementStart);
					result.put("gmtAnnouncementEnd", gmtAnnouncementEnd);
					result.put("coverType", coverType);
					result.put("origin", origin);
					result.put("author", author);
					result.put("coverMapList", coverMapList);
					result.put("extend", extendHashMap);
//					if (null != pageType && pageType.equals("checkPage")) {
//						result.put("url", serverUrl + "website/article/get-pc-template-render-content?articleId=" + articlePO.getId());
//					} else {
						result.put("url", url.replace("\\", "/"));
//					}
					result.put("serverUrl", serverUrl);
					this.binds(result);
					this.doBodyRender();
				}
			}
		}


	}

	/**
	 * 标签文档
	 * @return
	 */
	public static TagDocObject doc() {
		TagDocObject tagDocObject = new TagDocObject();
		tagDocObject.setTagName("articleList");
		tagDocObject.setDesc("文章列表标签");
		tagDocObject.setExample("<#articleList serverUrl=\"${serverUrl}\" columnId=\"${column.columnId}\" page=\"${column.page}\" dm=\"${dm}\" pageType=\"${pageType}\" limit=\"${column.limit}\"  var=\"data\">" +
				"        <li class=\"news-item\">\n" +
				"          <a href=\"${data.url!}\" >\n" +
				"            <span class=\"cricle-li\"></span>\n" +
				"            <span\n" +
				"              class=\"new-inner\">${data.title!}</span>\n" +
				"            <span class=\"news-date\">${data.releaseTimeMonthDay!}</span>\n" +
				"          </a>\n" +
				"        </li>\n" +
				"\t\t</#articleList>");

		tagDocObject.setParamDesc("columnId：所属栏目id\n" +
				"serverUrl：资讯发布系统的域名\n" +
				"dm：站点域名\n" +
				"pageType：用于标识是生成静态页面还是预览（预览：checkPage，生成：null或staticPage）\n" +
				"page：页码\n" +
				"limit(必填)：页条目数\n" +
				"--------- var: 标签的数据结果集 ---------\n" +
				"title：文章标题\n" +
				"releaseTime：发布时间(年月日时分秒)\n" +
				"releaseTimeMonthDay：发布时间(月份和日期)\n" +
				"attribute：文章属性(文字WEN_ZI,图片TU_PIAN,视频SHI_PIN)\n" +
				"gmtAnnouncementStart：公告开始时间\n" +
				"gmtAnnouncementEnd：公告结束时间\n" +
				"coverType：封面图类型(单图DAN_TU,多图DUO_TU,横图HENG_TU)\n" +
				"coverMapList：封面图集合\n" +
				"origin：来源\n" +
				"author：作者\n" +
				"content：内容\n" +
				"extend：扩展字段(data.extend.xxx)\n" +
				"url：跳转链接");

		tagDocObject.setOtherDesc("无");

		return tagDocObject;
	}

}
